<?php

namespace app\admin\controller;

use app\common\model\Classes;
use app\common\model\ClassesStu;
use app\common\model\ClassKaoqinLog;
use app\common\model\MoneyLog;
use app\common\model\Student as StudentModel;
use app\common\model\StudentFankui;
use app\common\model\StudentKaoqin;
use app\common\model\StudentKaoqinRemark as StudentKaoqinRemarkModel;
use app\service\MsgService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Controller;
use app\common\model\Manager as ManagerModel;
use app\common\model\User;

//use vaptcha\Vaptcha;
use think\Db;
use think\Loader;
use GuzzleHttp\Client;
use app\common\model\Config;
use vaptcha\Vaptcha;
use app\common\model\ManagerGongzi;
use app\common\model\Manager;
use app\common\model\ManagerStudent;
use app\common\model\Student;

class Login extends Controller
{

    public function __construct()
    {
        Loader::import("vaptcha.vaptcha", EXTEND_PATH, '.class.php');
        parent::__construct();
        config(Config::getConfig());
    }

    public function index()
    {
        $this->assign('data', [
            'type' => 'click',  //展示方式，默认为嵌入式
            'vid' => config('vaptcha_id')
        ]);
        return view();
    }


    public function gongzi()
    {
        //当前月份
        $month = date('Y-m');
        // 配置信息
        $config = Config::getConfig();
        // 管理员信息
        $manager = Manager::getAll([]);

        // 先查看是否已经生成当月工资条
        $where = [
            'time' => $month
        ];
        $gongzi = ManagerGongzi::getColumn($where, 'mid');

        // 生成工资当月工资列表
        $time = time();
        foreach ($manager as $v) {
            if (!in_array($v['id'], $gongzi)) {
                // 招新人数
                $zhaoxin_where = array(
                    'time' => array('eq', $month),
                    'mid' => array('eq', $v['id'])
                );
                $zhaoxin = ManagerStudent::getCount($zhaoxin_where);

                //课时
                $keshi_where = array(
                    'time' => array('like', $month . '%'),
                    'manager_name' => array('eq', $v['name'])
                );
                $keshi = StudentKaoqin::getCount($keshi_where);
                $save = array(
                    'jichu' => $config['jichu_gongzi'],
                    'zhaoxin' => $config['zhaoxin_gongzi'] * $zhaoxin,
                    'keshi' => $config['keshi_gongzi'] * $keshi,
                    'time' => $month,
                    'mid' => $v['id'],
                    'name' => $v['name'],
                    'create_time' => $time,
                    'update_time' => $time
                );
                ManagerGongzi::setInsertGetId($save);
            }

        }

    }

    public function test5()
    {
// 上一月
        _pr(1);
        $l_y = date('m')==1?date('Y')-1:date('Y');
        $l_m = 4;
        $l_m = $l_m<10?'0'. $l_m:$l_m;
        $l_d = date('t',strtotime($l_y . '-' . $l_m . '-1'));//上一月最后一天
        $last = $l_y . '年' . $l_m . '月';

        // 班级信息
        $class = $list_s = $list = array();
        $classes = Classes::getColumn([], 'id,week,name');
        foreach ($classes as $value) {
            $class[$value['week']][] = $value['id'];
        }

        $l_w = date('w',strtotime($l_y . '-' . $l_m . '-' . '1'));
        $l_w = $l_w==0?7:$l_w;


        for($i=1;$i<=$l_d;$i++){
            $date = date('Y-m-d', strtotime($l_y . '-' . $l_m . '-' . $i));
            $w = date('w', strtotime($date));
            $w = $w == 0 ? 7 : $w;
            $where = [
                'time' => ['=', $date],
            ];
            $kaoqin = ClassKaoqinLog::getColumn($where, 'cid');
            $kaoqin = [];
            $cl = [];
            if ($class[$w]) {
                foreach ($class[$w] as $c) {
                    if (!in_array($c, $kaoqin)) {
                        $cl[] = $classes[$c];
                    }
                }
            }
            $list_s[] = [
                'w' => $w,
                'd' => $i,
                'date' => $date,
                'log' => $cl
            ];
        }
        _pr($list_s);
        foreach ($list_s as $k => $v) {
//            $list = $this->scorelog($v['data']);
//            _pr($list);
//            foreach ($v['log'] as $k1 => $v1) {
//
//            }
        }

    }

    public function scorelog($time='')
    {
//        $input['update_time'] = ['2025-04-01','2025-04-15'];
//        $input['excel']=1;
            return $time;
            if ($time) {
                $where['time'] = array('eq',$time);
            }
            return $where;
            $page = 1;
            $list = StudentKaoqin::getGroupby($where, $page, 10000, 'time asc', '*', 'thumb');
            $total = StudentKaoqin::getGroupByCount($where, 'thumb');

            foreach ($list as $k => $v) {
                $stu_list_sid_where = array(
                    'content' => $v['content'],
                    'thumb' => $v['thumb']
                );
                $stu_list_sid = StudentKaoqin::getColumn($stu_list_sid_where, 'sid');
                $stu_list = [];
                if ($stu_list_sid) {
                    $stu_list = StudentModel::getColumn(['id' => ['in', $stu_list_sid]], 'id,name,create_time');
                }
                $list[$k]['stu_list'] = $stu_list;
                $list[$k]['total'] = sizeof($stu_list);
                $all += $list[$k]['total'];

                $list[$k]['classesInfo'] = Classes::getAll(['id' => ['in', $v['cid']]], 'id desc', 'id,name,create_time');
                //班级内全部学生
                $class_stu = ClassesStu::getAll(['cid' => ['in', $v['cid']]], 'cid desc', 'sid,cid');
                //未出勤学生
                $weichuqin_sids = [];
                if ($class_stu && $v['cid']) {
                    foreach ($class_stu as $s) {
                        if (!in_array($s['sid'], $stu_list_sid))
                            $weichuqin_sids[] = $s['sid'];
                    }
                    $wcq_stu_list = StudentModel::getColumn(['id' => ['in', $weichuqin_sids]], 'id,name,create_time');
                    $wcq_remark_sids = StudentKaoqinRemarkModel::getColumn(['img' => ['eq', $v['thumb']]], 'sid');
                    $jishu=0;
                    foreach ($wcq_stu_list as $wkk => $wv) {
                        $wcq_stu_list[$wkk]['coach_status'] = in_array($wv['id'], $wcq_remark_sids) ? false : true;
                        if($wcq_stu_list[$wkk]['coach_status'])
                            $jishu++;
                    }

                    $list[$k]['wcq_stu_list'] = $wcq_stu_list;
                    $list[$k]['weibeizhu'] = $jishu;
                } else {
                    $list[$k]['wcq_stu_list'] = [];
                }
            }
            return $list;
//                $file = $this->exportKaoqin($list);
//                return returnJson(0, '', $file);


    }

    protected function exportKaoqin($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrData = [
            ['日期', '班级', '人数', '教练', '备注', '考勤不通过']
        ];
        foreach ($list as $k => $v) {
            $banji = $v['classesInfo']?$v['classesInfo'][0]['name']:'';
            $weibeizhu = $v['weibeizhu']?$v['weibeizhu'] . '人未备注':'';
            $arrData[] = [
                $v['time'],$banji, $v['total'], $v['manager_name'], $v['content'], $weibeizhu
            ];
        }

        $sheet->fromArray($arrData, NULL);
        $writer = new Xlsx($spreadsheet);
        $name = '考勤信息-' . date('Y-m',strtotime($list[0]['time']))  . ".xlsx";
        $path = ROOT_PATH . "public" . DS . "cache" . DS . $name;
        $writer->save($path);
        return request()->domain() . "/cache/" . $name;
    }

    public function test4()
    {
//        $s = Student::getAll([]);
//        foreach ($s as $value){
//            $join_time = date('Y-m-d',strtotime($value['join_time']));
//
//            $join_time = str_replace('年','-',$join_time);
//            $join_time = str_replace('月','-',$join_time);
//            $join_time = str_replace('日','',$join_time);
//            $join_time = str_replace(' ','',$join_time);
//            $join_time = str_replace('号','',$join_time);
//            $join_time = str_replace('.','-',$join_time);
//            $save = [
//                'join_time' =>$join_time
//            ];
//            Student::update($save,['id'=>$value['id']]);
//            _pr(1);
//        }
    }



    public function test3()
    {


        $list = StudentFankui::getAll([]);
        foreach ($list as $value){
            echo '<pre>';
            $student = Student::getOne(['id'=>['eq',$value['sid']]]);
            $birth = $student['birth'];
            $birth = str_replace('年','-',$birth);
            $birth = str_replace('月','-',$birth);
            $birth = str_replace('日','',$birth);

            $jm = $this->getMonthNum($student['join_time'],$value['date'].'-01');
            $bm = $this->getMonthNum($birth,$value['date'].'-01');
            $qiuling = floor($jm/12)?floor($jm/12) . '年':'';
            $qiuling .= ($jm%12)?($jm%12). '月':'';
            $age = ceil($bm/12);
            $save = array(
                'qiuling' =>$qiuling,
                'age' =>$age,
                'manager_name' =>Manager::getValue(['id'=>$value['mid']],'name'),
                'cishu' =>StudentKaoqin::getCount(['sid'=>$value['sid'],'time'=>['like',$value['date'].'%']],'id'),
                'name' =>$student['name']
            );
            StudentFankui::update($save,['id'=>$value['id']]);
        }
//        _pr($list);
    }



//    public function test1(){
//        $student = \app\common\model\Student::getAll([],'','id,pay_time,lose_time,class_hour,has_class_hour');
////        var_dump($student); die;
//        foreach ($student as $value){
//            $money_log = MoneyLog::getCount(['sid' => ['eq',$value['id']],'create_time'=>[ ['>=',$value['pay_time']] ]]);
//            \app\common\model\Student::update(['has_class_hour'=>$money_log],['id'=>$value['id']]);
//        }
//    }

    public function test1()
    {
//        _pr(1);
        $n = './upload/1.txt';
        if (file_exists($n)) {
            $fp = fopen($n, 'r+');
            $d = [];
            while (!feof($fp)) {
                $data = fgets($fp);
                $data = explode(' ', $data);
                $d[] = $data;
            }
            fclose($fp);
            foreach ($d as $k => $value) {
                $d[$k] = array(
                    'name' => '暑假' . str_replace(chr(13).chr(10),'',$value[0]),
                    'month' => 2,
                    'pay_time' => '1751370000',
                    'lose_time' => '1756656000',
                    'class_hour' => 0,
                    'has_class_hour' => 0,
                );
                $id = Db::name('student')->insertGetId($d[$k]);
                $a = array(
                    'sid' => $id,
                    'cid' => 120,
                    'create_time' => time(),
                    'update_time' => time()
                );
                Db::name('classes_stu')->insert($a);
            }

        }
    }

    public function test2()
    {
        _pr(2);
        $where = [
            'join_time' => 'is null'
        ];
        $data = Db::name('student')->where($where)->select()->toArray();
//        $fp = fopen('2.txt', 'w');
//        fclose($fp);
//        $fp = fopen('2.txt', 'r+');
//        foreach ($data as $value) {
//            fwrite($fp, $value['name'] . "\r\n");
//        }
//        fclose($fp);
        _pr($data);
    }

    public function test()
    {
         _pr(3);
        $where = [
            'type' => ['in', ['kaoqin']],
//            'type' => ['in', ['kaoqin']],
//            'id'=>['eq',625299],
//            'type' => ['in', ['delKaoqin']] ,
//            'type' => ['in', ['studentEdit', 'delKaoqin', 'kaoqin']],
//            'type' => ['in', ['studentEdit']],
//            'data' => ['like', '%崔安一%']
//        'api'=>['like','%admin/student/student_edit%']
            'remark' => array('eq','263')
//           'data' => array('like','%:396,%')
            // 'remark' => array('neq','null');

        ];
        $page = input('page',1);
        $start = ($page-1)*5000;
        $data = Db::name('loginfo')->where($where)->limit($start, 5000)->order('id desc')->select()->toArray();

//        $data = json_decode($data[0]['data'],true)['student_new'];
//        Db::name('student')->insert($data);
        $data1 = array();
        echo sizeof($data);
        foreach ($data as $k => $v) {
            $data1 = json_decode($v['data'], true);
            $data[$k]['data1'] = $data1;
            if(isset($data1['student_old'])){
                if($data1['student_old']['name'] == '张宇恒'){
                    // _pr($data);
                    // _pr($data1['student_old']);
                }
            }
        }
        // _pr(1);
        $data2 = $data[0]['data1']['student_new'];
         _pr($data2);
    //    Student::($data2);
//        _pr($data);
       Db::name('student')->insert($data2);
       _pr(1);
//        Db::name('student')->insert($data2);
//        die();
//        $manage = Db::name('manager')->column( 'id,name');
        $sid = [];
        foreach ($data as $k => $v) {
            $data1 = json_decode($v['data'], true);
//            $data[$k]['name'] = isset($manage[$v['info']])?$manage[$v['info']]:'';
            $sid[] = $data[$k]['data1']['student_old']['id'];
        }
//        Db::name('student')->insert($data1);
        _pr($data1);
        $where = [
            'sid' => ['=', 270],
//            'thumb'=>['=','http://qiniu.xiyuezuqiu.cn/xyxiyuezuqiucn/20230510/1849016898.jpg']

        ];
//        $data = Db('student_kaoqin')->where($where)->order('id desc')->limit(200)->select()->toArray()   ;
        _pr($data);
    }

    public function dologin()
    {
        $input = input();

//        if (!$input['token']) {
//            return returnJson(1, '请填写token');
//        };

//        $client = new Client([]);
//        $response = $client->post('http://api.vaptcha.com/v2/validate', [
//            'form_params' => [
//                'id' => config('vaptcha_id'),
//                'secretkey' => config('vaptcha_key'),
//                'scene' => '',
//                'token' => $input['token'],
//                'ip' => ''
//            ]
//        ]);
//        $response = $client->post('http://0.vaptcha.com/verify', [
//            'form_params' => [
//                'id' => config('vaptcha_id'),
//                'secretkey' => config('vaptcha_key'),
//                'scene' => $input['scene'],
//                'token' => $input['token'],
//                'ip' => ''
//            ]
//        ]);

//        $body = $response->getBody();
//        $result = json_decode((string)$body, true);
//        if ($result['success'] == 0) {
//            return returnJson(1, '验证码错误');
//        }

        if (!$input['name'] || !$input['password']) {
            return returnJson(1, '请填写用户名和密码');
        }

        $manager = ManagerModel::getOne([
            'name' => $input['name']
        ]);

        if (!$manager || createPassword($input['password']) != $manager['password']) {
            return returnJson(1, '密码错误');
        }


        session('manager', $manager);
        return returnJson(0, '登陆成功', '/w');
    }

    /**
     * 验证
     */
    public function vaptcha()
    {
        if (isset($_REQUEST['offline_action'])) {
            if (isset($_GET['v'])) {
                echo Vaptcha::offline($_GET['offline_action'], $_GET['callback'], $_GET['v'], $_GET['knock']);
            } else {
                echo Vaptcha::offline($_GET['offline_action'], $_GET['callback']);
            }
        } else {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                $token = $_POST['token'];
                $scene = $_POST['scene'];
                $result = json_decode(Vaptcha::validate($token, $scene), true);
                return $result;
                if ($result['success'] == 0) {
                    return returnJson(1, '验证码错误');
                }
                print_r($result);
            }
        }
    }


    public function quit()
    {
        session('manager', null);
        return returnJson(2, '已退出', '/w');
    }

}
